<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <pre>
    // 例如将 input 转成output的形式
    let input = [
        {
            id: 1, val: '学校', parentId: 0
        }, {
            id: 2, val: '班级1', parentId: 1
        }, {
            id: 3, val: '班级2', parentId: 1
        }, {
            id: 4, val: '学生1', parentId: 2
        }, {
            id: 5, val: '学生2', parentId: 2
        }, {
            id: 6, val: '学生3', parentId: 3
        },
    ]
     
    let output = {
        id: 1,
        val: '学校',
        children: [{
            id: 2,
            val: '班级1',
            children: [
                {
                    id: 4,
                    val: '学生1',
                    children: []
                },
                {
                    id: 5,
                    val: '学生2',
                    children: []
                }
            ]
        }, {
            id: 3,
            val: '班级2',
            children: [{
                id: 6,
                val: '学生3',
                children: []
            }]
        }]
    }
</pre
    >
  </body>

  <script>
    let input = [
      {
        id: 1,
        val: "学校",
        parentId: 0,
      },
      {
        id: 2,
        val: "班级1",
        parentId: 1,
      },
      {
        id: 3,
        val: "班级2",
        parentId: 1,
      },
      {
        id: 4,
        val: "学生1",
        parentId: 2,
      },
      {
        id: 5,
        val: "学生2",
        parentId: 2,
      },
      {
        id: 6,
        val: "学生3",
        parentId: 3,
      },
    ];

    /* 使用递归的方法 */
    function arrToTree(arr, id) {
      // 保存结果数组
      const res = [];
      // 遍历原数组arr
      for (const item of arr) {
        if (item.parentId === id) {
          // 找到当前id的子元素
          // 插入子元素，每个子元素的children通过回调生成
          const obj = { ...item };
          // 删除 parentId
          delete obj.parentId;
          res.push({
            ...obj,
            children: arrToTree(arr, item.id),
          });
        }
      }
      return res;
    }

    console.log(arrToTree(input, 0));
  </script>
</html>
